package com.sunseen.capacitormachine.modules.query;

import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.databinding.ViewDataBinding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.databinding.FragmentQueryCapacitorCurveBinding;
import com.sunseen.capacitormachine.modules.query.bean.IVBean;

import java.util.ArrayList;
import java.util.List;

public class QueryCapacitorCurveFragment extends BaseFragment {

    private String uid = "";

    public void setUniqueId(String uid) {
        this.uid = uid;
    }

    @Override
    protected int setLayout() {
        return R.layout.fragment_query_capacitor_curve;
    }

    FragmentQueryCapacitorCurveBinding binding;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        binding = (FragmentQueryCapacitorCurveBinding) viewDataBinding;
        binding.toolBar.setNavigationOnClickListener((v) -> pop());
        initChart();
        queryIVData(curPage + 1);
        binding.queryNextHourBtn.setOnClickListener((v) -> {
            if (curPage < totalPage) {
                hideProgressBar(false);
                queryIVData(curPage + 1);
            } else {
                Toast.makeText(_mActivity, "第" + curPage + "页，共" + totalPage + "页", Toast.LENGTH_SHORT).show();
            }
        });
        binding.queryUpHourBtn.setOnClickListener((v) -> {
            if (curPage > 1) {
                hideProgressBar(false);
                queryIVData(curPage - 1);
            } else {
                Toast.makeText(_mActivity, "第" + curPage + "页，共" + totalPage + "页", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initChart() {
        LineChart lineChart = binding.lineChart;
        lineChart.setNoDataText("");
        lineChart.getDescription().setEnabled(false);
        lineChart.setPinchZoom(true);
        lineChart.setBackgroundColor(Color.TRANSPARENT);
        Legend legend = lineChart.getLegend();
        legend.setForm(Legend.LegendForm.CIRCLE);
        legend.setTextSize(17f);
        legend.setTextColor(Color.BLACK);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(true);
        legend.setXOffset(30f);
        legend.setYOffset(20f);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setAxisLineColor(getResources().getColor(R.color.colorAccent));
        xAxis.setAxisLineWidth(3f);
        xAxis.setTextSize(15f);
        xAxis.setTextColor(Color.BLACK);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(true);
        xAxis.setAxisMinimum(0f);
        xAxis.mAxisRange = 1200;
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                if (value != 0f) {
                    return (int) value + "s";
                } else {
                    return "";
                }
            }
        });

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setAxisLineColor(getResources().getColor(R.color.green));
        leftAxis.setTextSize(15f);
        leftAxis.setAxisLineWidth(2f);
        leftAxis.setAxisMaximum(600f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawGridLines(false);
        leftAxis.setGranularityEnabled(false);

        YAxis rightAxis = lineChart.getAxisRight();
        rightAxis.setAxisLineColor(getResources().getColor(R.color.red_light));
        rightAxis.setTextSize(15f);
        rightAxis.setAxisLineWidth(2f);
        rightAxis.setAxisMaximum(3000f);
        rightAxis.setAxisMinimum(0f);
        rightAxis.setDrawGridLines(false);
        rightAxis.setGranularityEnabled(false);
    }

    private int curPage = 0;
    private int totalPage = 0;

    private void queryIVData(int page) {
        RestClient.builder().url(HttpUtil.ivData)
                .params("uid", uid)
                .params("page", page)
                .params("per_page", 7200)
                .success((String response) -> {
                    JSONObject jsonObject = JSON.parseObject(response);
                    if (jsonObject.getInteger("status") == 1) {
                        JSONObject dataObj = jsonObject.getJSONObject("data");
                        if (dataObj != null) {
//                            JSONArray jsonArray = dataObj.getJSONArray("array");
                            String str = dataObj.getString("array");
                            JSONArray jsonArray = JSON.parseArray(str);
                            if (totalPage == 0) {
                                totalPage = dataObj.getIntValue("total_page");
//                                binding.hourTv.setText(String.format(getString(R.string.aging_hour_format), "" + totalPage));
                            }
                            List<IVBean> ivBeanList = jsonArray.toJavaList(IVBean.class);
                            if (ivBeanList.size() > 0) {
                                if (curPage == 0) {
                                    drawChart(ivBeanList);
                                } else {
                                    addLast(ivBeanList);
                                }
                                curPage++;
                            } else {
                                Toast.makeText(_mActivity, "无电流电压数据", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(_mActivity, "查询电流电压数据失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(_mActivity, "查询电流电压数据失败", Toast.LENGTH_SHORT).show();
                    }
                    hideProgressBar(true);
                })
                .failure(() -> {
                    hideProgressBar(true);
                    Toast.makeText(_mActivity, "查询电流电压数据失败", Toast.LENGTH_SHORT).show();

                })
                .error((int code, String msg) -> {
                    hideProgressBar(true);
                    Toast.makeText(_mActivity, "查询电流电压数据错误", Toast.LENGTH_SHORT).show();
                    Log.e("test", "code = " + code + " msg = " + msg);
                })
                .build()
                .get();
    }

    private LineDataSet set1;
    private LineDataSet set2;

    private void drawChart(List<IVBean> ivBeanList) {
        final List<Entry> vList = new ArrayList<>();
        final List<Entry> iList = new ArrayList<>();
        int i = 0;
        for (IVBean bean : ivBeanList) {
            vList.add(new Entry(i, bean.getV()));
            iList.add(new Entry(i, bean.getI()));
            i++;
        }
        set1 = new LineDataSet(vList, "电压(V)");
        set2 = new LineDataSet(iList, "电流(μA)");
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
        int greenColor = getResources().getColor(R.color.green);
        set1.setColor(greenColor);
        set1.setCircleColor(greenColor);
        set1.setLineWidth(2f);
        set1.setCircleRadius(1f);
        set1.setFillColor(greenColor);
        set1.setHighLightColor(Color.rgb(244, 177, 177));
        set1.setDrawCircleHole(false);

        set2.setAxisDependency(YAxis.AxisDependency.RIGHT);
        int redColor = getResources().getColor(R.color.red_light);
        set2.setColor(redColor);
        set2.setCircleColor(redColor);
        set2.setMode(LineDataSet.Mode.LINEAR);
        set2.setLineWidth(2f);
        set2.setCircleRadius(1f);
        set2.setFillColor(redColor);
        set2.setHighLightColor(Color.rgb(244, 177, 177));
        set2.setDrawCircleHole(false);

        LineData lineData = new LineData(set1, set2);
        lineData.setValueTextColor(Color.BLACK);
        lineData.setValueTextSize(13f);
        binding.lineChart.setData(lineData);
        binding.lineChart.setVisibleXRangeMaximum(1200);
        binding.lineChart.moveViewToX(set1.getEntryCount());
    }

    private void addLast(List<IVBean> ivBeanList) {
        LineData data = binding.lineChart.getData();
        for (IVBean ivBean : ivBeanList) {
            data.addEntry(new Entry(set1.getEntryCount(), ivBean.getV()), 0);
            data.addEntry(new Entry(set2.getEntryCount(), ivBean.getI()), 1);
        }
        data.notifyDataChanged();
        binding.lineChart.notifyDataSetChanged();
        binding.lineChart.setVisibleXRangeMaximum(1200);
        binding.lineChart.moveViewToX(set1.getEntryCount());
    }

    private void hideProgressBar(boolean hide) {
        binding.queryProgressBar.setVisibility(hide ? View.GONE : View.VISIBLE);
        binding.queryingTv.setVisibility(hide ? View.GONE : View.VISIBLE);
    }
}
